#include <sys/types.h> 
#include <sys/stat.h> 
#include <string.h> 
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h> 
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <assert.h>
#include <linux/i2c.h>
#include <linux/i2c-dev.h>
#include <linux/types.h>
#include "cetc14-iic.h"

int higher2lower(char c);
int htoi(char s[]);


#define creat_value(baud,idle,path,tx,timeout) (unsigned int)(((baud & 0xF) << 28) + ((idle & 0x3) << 24) + ((path & 0x7) << 16) + ((tx & 0x1) << 23) + (timeout & 0xF))

int main(int argc, char *argv[]) 
{
	unsigned int tempval,tempval1;
	int i,count;
	
	unsigned int port, baud, idle, path, tx, timeout;

	unsigned int reg_address;
	unsigned int value;
	unsigned int sdi_index;

	count = 0;
	tempval = 0;
	tempval1 = 0;
	port = htoi(argv[1]);
	baud = htoi(argv[2]);
	idle = htoi(argv[3]);
	path = htoi(argv[4]);
	tx = htoi(argv[5]);
	timeout = htoi(argv[6]);
	sdi_index=htoi(argv[7]);

	reg_address = 0x10108 + 0x100 * port;
	iic_access(sdi_index,0x58,reg_address,&tempval,1);

	switch(baud)
	{
		case 1:
			value = creat_value(1,idle,path,tx,timeout);
			break;
		case 2:
			value = creat_value(2,idle,path,tx,timeout);
			break;
		case 3:
			value = creat_value(3,idle,path,tx,timeout);
			break;
		case 5:
			value = creat_value(4,idle,path,tx,timeout);
			break;
		case 6:
			value = creat_value(5,idle,path,tx,timeout);
			break;
		case 10:
			value = creat_value(8,idle,path,tx,timeout);
			break;
		default:
			printf("baud value is %#x, invalide.\n");
	}
	reg_address = 0x10108 + 0x100 * port;
	iic_access(sdi_index,0x58,reg_address,&value,0);
	
	reg_address = 0x10108 + 0x100 * port;
	iic_access(sdi_index,0x58,reg_address,&tempval,1);

	return 0;
}

int higher2lower(char c)
{
	if(c >= 'A' && c <= 'Z')
		return c + 'a' - 'A';
	else
	  return c;
}

int htoi(char s[])
{
	int i;
	int n = 0;
	if(s[0] == '0' && (s[1] == 'x' || s[1] == 'x'))
	  i = 2;
	else
	  i = 0;
	for(;(s[i] >= '0' && s[i] <= '9') || (s[i] >= 'a' && s[i] <= 'f') \
			|| (s[i] >= 'A' && s[i] <= 'F'); ++i)
	{
		if(higher2lower(s[i] > '9'))
		{
			n = 16 * n +(10 + higher2lower(s[i]) - 'a');
		}
		else
		  n = 16 * n + (higher2lower(s[i] - '0'));
	}
	return n;
}
